<template>
  <Form ref="patchForm" class="xtx-form" :validation-schema="schema" v-slot="{ errors }" autocomplete="off">
    <div class="xtx-form-item">
      <div class="field">
        <i class="icon iconfont icon-user"></i>
        <Field :class="{ err: errors.account }" v-model="form.account" name="account" class="input" type="text"
          placeholder="请输入用户名" />
        <div v-if="errors.account" class="error"><i class="iconfont icon-warning" />{{ errors.account }}</div>
      </div>
    </div>
    <div class="xtx-form-item">
      <div class="field">
        <i class="icon iconfont icon-phone"></i>
        <Field :class="{ err: errors.mobile }" v-model="form.mobile" name="mobile" class="input" type="text"
          placeholder="请输入手机号" />
        <div v-if="errors.mobile" class="error"><i class="iconfont icon-warning" />{{ errors.mobile }}</div>
      </div>
    </div>
    <div class="xtx-form-item">
      <div class="field">
        <i class="icon iconfont icon-code"></i>
        <Field :class="{ err: errors.code }" v-model="form.code" name="code" class="input" type="text"
          placeholder="请输入验证码" />
        <button ref="codeCom" @click.prevent="send" class="code">
          {{ time === 0 ? '发送验证码' : `${time}s后发送` }}
        </button>
        <div v-if="errors.code" class="error"><i class="iconfont icon-warning" />{{ errors.code }}</div>
      </div>
    </div>
    <div class="xtx-form-item">
      <div class="field">
        <i class="icon iconfont icon-lock"></i>
        <Field :class="{ err: errors.password }" v-model="form.password" name="password" class="input" type="password"
          placeholder="请输入密码" />
        <div v-if="errors.password" class="error"><i class="iconfont icon-warning" />{{ errors.password }}</div>
      </div>
    </div>
    <div class="xtx-form-item">
      <div class="field">
        <i class="icon iconfont icon-lock"></i>
        <Field :class="{ err: errors.rePassword }" v-model="form.rePassword" name="rePassword" class="input"
          type="password" placeholder="请确认密码" />
        <div v-if="errors.rePassword" class="error"><i class="iconfont icon-warning" />{{ errors.rePassword }}</div>
      </div>
    </div>
    <a @click="patch" href="javascript:;" class="submit">立即提交</a>
  </Form>
</template>

<script setup>
import { reactive, ref, defineProps, onUnmounted } from 'vue'
import { userQQPatchCode, userQQPatchLogin } from '@/api/login'
import { Form, Field } from 'vee-validate'
// 从配置选项中导入公用的验证规则
import { myFormValidate } from '@/config'
import Message from '@/components/library/message'
import { useIntervalFn } from '@vueuse/core'
import { useStore } from 'vuex'
import { useRouter, useRoute } from 'vue-router'
const store = useStore()
const route = useRoute()
const router = useRouter()
const props = defineProps({
  unionId: {
    type: String,
    default: ''
  }
})
// 表单数据对象
const form = reactive({
  account: null,
  mobile: null,
  code: null,
  password: null,
  rePassword: null
})
// 表单校验规则
const schema = {
  // 注册时用户的验证需要保证用户名不能重复
  account: myFormValidate.accountApi,
  mobile: myFormValidate.mobile,
  code: myFormValidate.code,
  password: myFormValidate.password,
  rePassword: myFormValidate.rePassword
}
// 表单对象
const patchForm = ref(null)
// 登录时发送短信验证码
const codeCom = ref(null)
const time = ref(0)
// 定时器的处理函数
// pause 暂停 resume 开始
// useIntervalFn(回调函数,执行间隔,是否立即开启)
const { pause, resume } = useIntervalFn(() => {
  // 定时器的业务
  time.value--
  if (time.value <= 0) {
    //  停止定时器
    pause()
    // 发送按钮可用
    codeCom.value.disabled = false
    time.value = 0
  }
}, 1000, false)
// 组件销毁时，清除定时器
onUnmounted(() => {
  pause()
})
// 发送登录验证码
function send() {
  // 需要对用户填写的手机号码做校验
  //  由于点击发送验证码的行为，并不需要手机号码选项失去焦点或者是提交表单时触发，主动触发表单的验证规则
  const mobileValid = schema.mobile(form.mobile)
  if (mobileValid === true) {
    // 代表是标准的手机号码,可以发送短信
    userQQPatchCode(form.mobile).then(() => {
      // 设置倒计时时间
      time.value = 60
      // 禁用按钮
      codeCom.value.disabled = true
      // 开启定时器
      resume()
      // 提示
      Message({ type: 'success', text: '短信验证码发送成功' })
    }).catch(e => {
      Message({ type: 'error', text: e.response.data.message || '短信发送失败' })
    })
  } else {
    // 失败，使用vee的错误函数显示错误信息 setFieldError(字段,错误信息)
    patchForm.value.setFieldError('mobile', mobileValid)
  }
}
// 完善信息
async function patch() {
  const valid = await patchForm.value.validate()
  if (valid) {
    try {
      const { result } = await userQQPatchLogin({ unionId: props.unionId, ...form })
      // 1. 存储用户信息
      const { id, account, avatar, mobile, nickname, token } = result
      store.commit('user/setUser', { id, account, avatar, mobile, nickname, token })
      // 合并购物车
      store.dispatch('cart/mergeCart').then(() => {
        // 2. 跳转到来源页或者首页
        router.push((route.query.redirectUrl && decodeURIComponent(route.query.redirectUrl)) || store.state.user.currentPath || '/')
        // 3. 成功提示
        Message({ type: 'success', text: '完善信息成功' })
      })
    } catch (err) {
      Message({ type: 'error', text: '账号注册失败' })
    }
  } else {
    Message({ type: 'error', text: '校验失败', time: 5000 })
  }
}
</script>

<style scoped lang='less'>
.code {
  position: absolute;
  right: 0;
  top: 0;
  line-height: 50px;
  width: 120px;
  height: 50px;

  &:hover {
    cursor: pointer;
  }
}
</style>